import React, {useContext, useState} from "react";
import {Alert, Dimensions, ImageBackground, ScrollView, Text, TextInput, TouchableOpacity, View} from "react-native";
import LocaleContext from "../libs/locale";
import WalletContext, {checkPassword} from "../libs/wallet";
import redEnvelopeBG from '../assets/redEnvelope/redEnvelope2.png';
import BTN from '../assets/redEnvelope/BTN.png';
import {formartMoney, toDecimal2} from "../libs/helpers";
import {getTxInfo, getTxStatus, tokenTransfer, transfer} from "../libs/nodes";
import {addRedEnvelopeTx, addTx, getTxs as getPendingTxs, getTxs2, popTx, saveTX, saveTXone} from "../libs/pendingTxs";
import {constansts} from "../libs/constansts";
import {Icon, Input, ListItem} from "react-native-elements";
import NewTextInput from "../components/NewTextInput";
import {Net} from "./axios";
import {useFocusEffect} from "@react-navigation/native";

const {width, height} = Dimensions.get("window");

const RedEnvelope = ({navigation,route}:any)=>{
    const locale: any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [coverTxt,setCoverTxt] = useState((locale as any)._('RedEnvelope.Blessing'));
    const [num,setNum] = useState('');//红包个数
    const [amount,setAmount] = useState('');//红包金额
    const  coin = route?.params?.coin ||"SAT";
    const tokenAddress = route?.params?.tokenAddress || "";

    //红包转账详情及输入密码部分
    const [showTranInfo,setShowTranInfo] = useState(false);
    const [inputPassword,setInputPassword] = useState(false);
    const [pwdVisible, setPwdVisible] = useState(false);
    const [pwd, setPwd] = useState('');
    const [pwdError, setPwdError] = useState('');         //TODO 2021-03-07
    const [transfering, setTransfering] = useState(false);
    const RedEnvelopeAccount = 'dqhB9krjKeF8ffNsXrNt7tezJmrqeVdAP';//红包账户

    const checkInfo = () => {
        setPwdError("");
        if(constansts.RedEnvelopeShowTip)
        {
            Alert.alert("",locale._("RedEnvelope.SendingRedEnvelope"));
            return;
        }
        if(parseFloat(amount)<=0 || parseFloat(num)<=0 || amount==="" )
        {
            Alert.alert('',locale._("RedEnvelope.AlertNumOrTotal"));
            return;
        }
        if(parseFloat(num)>200)
        {
            Alert.alert('',locale._("RedEnvelope.AlertNum"));
            return;
        }
        if(parseFloat(amount)/parseFloat(num)<0.05)
        {
            Alert.alert('',locale._("RedEnvelope.AlertTotal"));
            return;
        }
        if(parseFloat(constansts.SATcount) < 0.002)
        {
            Alert.alert("",locale._("serviceChargeError"));
            return;
        }
        setPwdError("");
        setTransfering(false);
        setShowTranInfo(true);
    }

    const sendRedEnvelope = async () => {

        if(constansts.RedEnvelopeShowTip)
        {
            Alert.alert("","正在发送红包请稍等！");
            return;
        }
        if(parseFloat(amount)<=0 || parseFloat(num)<=0)
        {
            Alert.alert('',"请输入正确的金额或者数量！");
            return;
        }
        setTransfering(true);
        if (!checkPassword(wallet, pwd)) {
            setPwdError(locale?._('Import.passwordError'));
            setTransfering(false);
            return;
        }
        // console.log("访问url")
        await Net("http://101.36.122.116:8000/mypackage?getter="+wallet.address,"").then(async (res:any)=>{
            await sendTran();
        },err=>{
            setInputPassword(false)
            setTransfering(false);
            Alert.alert("",locale._("RedEnvelopeInfo.AlertSendFalse"))
        }).catch((Error:any)=>{
            setInputPassword(false)
            setTransfering(false);
            // console.log("Error了");
        })
    }
    const sendTran = async () => {
        try {
            // var testNet = await MyRedEnvelope(wallet.address);
            // console.log("testNet="+testNet);
            // if(JSON.stringify(testNet)==="Error")
            // {
            //     setInputPassword(false)
            //     setTransfering(false);
            //     Alert.alert("",locale._("RedEnvelope.SendError"))
            //     return ;
            // }
            var tx: any;
            if(tokenAddress=="" && coin=="SAT")
            {
                tx = await transfer(wallet.seed, wallet.address, RedEnvelopeAccount, formartMoney(amount, 2), '');
                constansts.RedEnvelopeType = "SAT";
            }
            else
            {
                var datam: any;
                let amountm = formartMoney(amount,2);
                datam = "transfer(\"" + RedEnvelopeAccount + "\"," + "\"" + amountm + "\")";
                // console.log("beforeTran amount="+amountm);
                tx = await tokenTransfer(wallet.seed, wallet.address, tokenAddress, datam,"", RedEnvelopeAccount);
                constansts.RedEnvelopeType = "Token";
            }

            if (tx.reason != 1) {
                // console.log("false reason=" + tx.reason + "     " + amount);
                Alert.alert(tx.reason.toString(), (locale as any)._('Assets.send.sendFail'));
                setTransfering(false);
            } else {
                await addTx(tx);
                await addRedEnvelopeTx(tx, num, parseFloat(amount).toString(),constansts.RedEnvelopeType,coin,tokenAddress);
                (constansts.tranRedEnvelope as any).push(tx);
                constansts.RedEnvelopeHash = tx.hash;
                constansts.RedEnvelopeNumber = parseInt(num).toString();
                constansts.RedEnvelopeTotal = parseFloat(amount).toString();
                constansts.RedEnvelopeShowTip = true;
                constansts.RedEnvelopeBless = coverTxt;
                constansts.RedEnvelopeTokenName = coin;
                Alert.alert('', locale._('Assets.send.sendSuccess'), [{
                    text: locale?._('Assets.send.OK'), onPress: () => {
                        setTransfering(false);
                        navigation.popToTop();
                        navigation.push('RedEnvelopeIndex');
                    }
                }]);//TODO 交易已广播 2021-03-06
            }

        } catch (e) {
            setInputPassword(false)
            setTransfering(false);
            Alert.alert("", locale._("RedEnvelope.SendError"))
            // console.log("发送红包出错了,或者网络有问题")
        }
    }
    //定时器处理交易
    // useFocusEffect(
    //     React.useCallback(() => {
    //         let t:any;
    //         let onOFF = true;
    //         const inwork = async()=>{
    //             var txx = await getTxs2();
    //             await txx.map(async (tx:any,index:number)=>{
    //                 let heightNow = "0";
    //                 if(tx.height !== -1 )
    //                 {
    //
    //                 }
    //                 else {
    //                     var txStatus = await getTxStatus(tx.hash);
    //                     if(txStatus == -1 || txStatus == 2)
    //                     {
    //                         return;
    //                     }
    //                     else if (txStatus === -2)
    //                     {
    //                         let res = await getTxInfo(tx.hash);
    //                         if(res.height === 0)
    //                         {
    //                             txx[index].height = 0;
    //                             await saveTXone(txx[index], "modify");
    //                         }
    //                         else if (res.height > 0)
    //                         {
    //                             await popTx(tx.hash);
    //                             return;
    //                         }
    //                         else if ( res === false && (((new Date().getTime())-tx.trantime)>(2*60*1000)) )
    //                         {
    //                             txx[index].height = -2;
    //                             await saveTXone(txx[index], "modify");
    //                             return;
    //                         }
    //                     }
    //                     else if(txStatus == 0)
    //                     {
    //                         txx[index].height = -2;
    //                         await saveTXone(txx[index], "modify");
    //                         return;
    //                     }
    //                     else if(txStatus == 1)
    //                     {
    //                         await popTx(tx.hash);
    //                         return;
    //                     }
    //                     else if(txStatus == 3)
    //                     {
    //                         txx[index].height = 0;
    //                         await saveTXone(txx[index], "modify");
    //                     }
    //                 }
    //             })
    //
    //             try {
    //                 const txs = await getPendingTxs();
    //             } catch (e) {
    //                 console.log('getPendingTxs inwork:', e);
    //             }
    //             t = null;
    //             if(!onOFF)
    //             {
    //                 return ;
    //             }
    //             t = setTimeout(()=>{inwork()},10*1000);
    //         }
    //         inwork();
    //         return ()=> {
    //             onOFF = false;
    //             clearTimeout(t)
    //         };
    //     }, [])
    // );


    return(
        <View >
            <ImageBackground source={redEnvelopeBG} style={{height:height,width:width}} >
                <ScrollView scrollEnabled={false}>
                <View style={{flex:1}} />
                </ScrollView>
                <View style={{height:0.58*height}}>
                    <TextInput
                        underlineColorAndroid={"transparent"}
                        placeholder={(locale as any)._('RedEnvelope.Blessing')}
                        allowFontScaling={true}
                        // onFocus={focus}
                        value={coverTxt}
                        onChangeText={
                            (value) => {
                                if(value.length>30)
                                {
                                    // console.log(value.length>40)
                                    setCoverTxt(value.slice(0,40));
                                    return;
                                }
                                setCoverTxt(value);
                            }
                        }
                        editable={true}
                        defaultValue={coverTxt}
                        style={{
                            width:"90%",
                            marginLeft:"5%",
                            marginRight:"5%",
                            // fontSize:16,
                            backgroundColor:"#fedbd5",
                            borderRadius:6,
                            textAlign:"center",
                            height:45,
                        }}
                    />
                    <ScrollView scrollEnabled={false}>
                        <View style={{width:"90%",height:height*0.28,backgroundColor:"white",alignSelf:"center",marginTop:10,borderRadius:10}}>
                            <View style={{marginLeft:5,marginRight:15,flexDirection:"row",marginTop:height*0.025}}>
                                <View style={{width:width*0.9,flexDirection:"row"}}>
                                    <Text style={{fontSize:width/360*15,marginTop:height*0.003,width:width*0.3,paddingLeft:5}}>
                                        {locale._("RedEnvelope.NumberOf")}
                                    </Text>
                                    {/*<Text style={{fontSize:16,fontWeight:"bold"}}> 1 个</Text>*/}
                                    <View style={{flexDirection:"row"}}>

                                        <NewTextInput num={num} setNum={setNum} locale={useContext(LocaleContext)} type={"1"}/>
                                        <View style={{width:width*0.14,flexDirection:"row",justifyContent:"flex-end"}}>
                                            <Text style={{marginLeft:width*0.05,fontSize:width/360*15}}>{(locale as any)._("RedEnvelope.Unit")}</Text>
                                        </View>
                                    </View>
                                </View>
                            </View>
                            <View style={{marginLeft:5,marginRight:15,flexDirection:"row",marginTop:12}}>
                                <Text style={{width:width*0.3,fontSize:width/360*15}}> {(locale as any)._("RedEnvelope.Type")} </Text>
                                <View style={{width:width*0.5,alignItems:"flex-start"}}>
                                    <Text style={{fontSize:width/360*15}}> {(locale as any)._("RedEnvelope.Type1")}</Text>
                                </View>
                            </View>
                            <View style={{marginLeft:5,marginRight:15,flexDirection:"row",marginTop:12}}>
                                <View style={{width:width*0.9,flexDirection:"row"}}>
                                    <Text style={{fontSize:width/360*15,marginTop:height*0.003,width:width*0.3,paddingLeft:5}}>
                                        {locale._("RedEnvelope.Amount")}
                                    </Text>
                                    {/*<Text style={{fontSize:16,fontWeight:"bold"}}> 999元</Text>*/}
                                    <View style={{flexDirection:"row"}}>
                                        <NewTextInput num={amount} setNum={setAmount} locale={useContext(LocaleContext)} type={"2"}/>
                                        <TouchableOpacity
                                            onPress={() => navigation.replace('SendSelectAsset', {receiver:"RedEnvelopeSelect"})}
                                            activeOpacity={1}
                                        >
                                            <View style={{width:width*0.19,flexDirection:"row",justifyContent:"flex-end",alignItems:"center"}}>
                                                <Text style={{fontSize:width/360*15}}>{coin} </Text>
                                                <Icon
                                                    name='chevron-right'
                                                    type='font-awesome-5'
                                                    size={12}
                                                />
                                            </View>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </View>
                            <View style={{flex:1,alignItems:"center",marginTop:20}}>
                                <Text style={{fontSize:width/360*35}}>{toDecimal2(parseFloat(amount || "0").toString())} {coin}</Text>
                            </View>
                        </View>
                        {/*<ImageBackground source={under} style={{width:"100%",height:height*0.28,marginTop:-height*0.15}}>*/}
                        <View style={{marginTop:height*0.10,justifyContent:"center"}}>
                            <TouchableOpacity style={{alignSelf:"center",justifyContent:"center"}} activeOpacity={0.6} onPress={checkInfo}>
                                <ImageBackground source={BTN} style={{width:width*0.6,height:height*0.1,alignItems:"center",justifyContent:"center",padding:10}}>
                                    <Text style={{fontSize:width/360*25,color:"#b01700",alignSelf:"center",paddingBottom:8,paddingLeft:3}}>
                                        {(locale as any)._("RedEnvelope.ButtonTitle")}
                                    </Text>
                                </ImageBackground>
                            </TouchableOpacity>
                            <View style={{}}>
                                {/*<Text style={{color:"#fec58d",alignSelf:"center",fontSize:width/360*15}}>{(locale as any)._("RedEnvelope.24HourTip")}</Text>*/}
                            </View>
                        </View>
                    {/*</ImageBackground>*/}
                    </ScrollView>
                </View>
                {
                    showTranInfo?
                        <View style={{marginTop: -height, alignItems: 'center'}}>
                            <View style={{width: '100%', height: height}}>
                                <View style={{
                                    alignItems: 'center',
                                    flex: 1,
                                    opacity: 0.5,
                                    backgroundColor: 'black'
                                }}>
                                    {/*上面阴影部分点击关闭详情窗口*/}
                                    <TouchableOpacity style={{height: height * 0.5, width: "100%"}}
                                                      onPress={()=>{setShowTranInfo(false)}}>

                                    </TouchableOpacity>
                                </View>
                                <View style={{
                                    width: "100%",
                                    backgroundColor: 'white',
                                    minHeight: 380,
                                }}>
                                    <View style={{
                                        flexDirection: 'row',
                                        paddingVertical: 20,
                                    }}>
                                        <Text style={{
                                            fontSize: 18,
                                            fontWeight: 'bold',
                                            textAlign: 'center',
                                            flex: 1
                                        }}>{locale?._('Assets.send.payDetailTitle')}</Text>
                                          {/*× 关闭详情窗口  */}
                                        <TouchableOpacity
                                            style={{position: 'absolute', padding: 20}}
                                            onPress={()=>{setShowTranInfo(false)}}>
                                            <Icon type='font-awesome' name='close' color='#333333FF'
                                                  size={24}/>
                                        </TouchableOpacity>
                                    </View>
                                    {/***交易金额**/}
                                    <View style={{
                                        height: 80,
                                        justifyContent: 'center',
                                        alignItems: 'center'
                                    }}>
                                        <Text
                                        style={{fontSize: 25, fontWeight: 'bold', textAlign: 'center'}}>
                                        -{formartMoney(amount,2)} {coin}
                                    </Text>

                                    </View>
                                    {/*<View style={ {height:1,backgroundColor:'#8a8a8a'}}/>*/}
                                    {/***收款账户**/}
                                    <ListItem bottomDivider>
                                        <Text style={{width: 100, fontSize: 18, textAlign: 'center'}}>
                                            {locale?._('Assets.send.payDetailReceiver')}
                                        </Text>
                                        <ListItem.Content>
                                            <ListItem.Title> {locale?._('RedEnvelope.RedEnvelopeAccount')}</ListItem.Title>
                                        </ListItem.Content>
                                    </ListItem>
                                    {/***付款账户**/}
                                    <ListItem bottomDivider>
                                        <Text style={{width: 100, fontSize: 18, textAlign: 'center'}}>
                                            {locale?._('Assets.send.payDetailTitleSender')}
                                        </Text>
                                        <ListItem.Content>
                                            <ListItem.Title>{wallet.address}</ListItem.Title>
                                        </ListItem.Content>
                                    </ListItem>
                                    {/***‘确定’按钮**/}
                                    <TouchableOpacity style={{
                                        width: 334,
                                        height: 40,
                                        justifyContent: 'center',
                                        backgroundColor: '#088DE8',
                                        alignItems: 'center',
                                        alignSelf: 'center' ,
                                        marginTop: 20,
                                        borderColor: '#088DE8',
                                        borderWidth: 1,
                                        borderRadius: 10
                                    }}
                                                      onPress={() => {
                                                          // this.state.showTranInfo = false;
                                                          // this.state.inputPassword = true;
                                                          setShowTranInfo(false)
                                                          setInputPassword(true)
                                                      }}>
                                        <Text style={{
                                            // marginTop: 160,
                                            fontSize: 20,
                                            textAlign: 'center',
                                            color: 'white'
                                        }}>{locale._('Assets.send.payDetailBtnOK')}</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                        :null
                }
                {
                    inputPassword?
                        <View style={{marginTop: -height, alignItems: 'center'}}>
                            <View style={{width: '100%', height: height}}>
                                <View style={{
                                    alignItems: 'center',
                                    flex: 1,
                                    backgroundColor: 'black',
                                    opacity: 0.5
                                }}>
                                    <TouchableOpacity style={{height: height * 0.5, width: "100%"}}
                                                      onPress={() => {setInputPassword(false)}}>
                                    </TouchableOpacity>
                                </View>
                                <View style={{
                                    backgroundColor: 'white',
                                    // borderTopLeftRadius: 27,
                                    // borderTopRightRadius: 27,
                                    minHeight: 280,
                                }}>
                                    <View style={{
                                        flexDirection: 'row',
                                        paddingVertical: 20,
                                    }}>
                                        <Text style={{
                                            fontSize: 18,
                                            fontWeight: 'bold',
                                            textAlign: 'center',
                                            flex: 1
                                        }}>{locale?._('Import.password')}</Text>
                                        <TouchableOpacity
                                            style={{position: 'absolute', padding: 20}}
                                            onPress={() => {setInputPassword(false)}}
                                        >
                                            <Icon type='font-awesome' name='close' color='#333333FF'
                                                  size={24}/>
                                        </TouchableOpacity>
                                    </View>
                                    <Input
                                        autoFocus={true}
                                        placeholder={locale?._('Assets.send.pwHint')}
                                        rightIcon={<Icon
                                            name={pwdVisible ? 'eye' : 'eye-off'}
                                            type='feather'
                                            onPress={() => {setPwdVisible(!pwdVisible)}}
                                        />}
                                        secureTextEntry={!pwdVisible}
                                        errorMessage={pwdError}
                                        onChangeText={value => {setPwd(value)}}
                                        // onFocus={()=>{setPWDfocus(true);}}
                                        // onBlur={()=>{setPWDfocus(false)}}
                                    />
                                    <View style={{flex: 1}}></View>
                                    <View style={{
                                        flexDirection: 'row',
                                        bottom: 0,
                                        marginTop: 10,
                                        marginBottom: 20,
                                        alignSelf: 'center'
                                    }}>
                                        {
                                            pwd
                                                ?
                                                <TouchableOpacity style={{
                                                    width: "96%",
                                                    height: 50,
                                                    marginBottom:10,
                                                    justifyContent: 'center',
                                                    backgroundColor: '#088DE8',
                                                    alignItems: 'center',
                                                    borderColor: '#088DE8',
                                                    borderWidth: 1,
                                                    borderRadius: 10
                                                }}
                                                                  disabled={transfering}
                                                                  onPress={sendRedEnvelope}>
                                                    <Text style={{
                                                        // marginTop: 160,
                                                        fontSize: 20,
                                                        textAlign: 'center',
                                                        color: 'white'
                                                    }}>{locale._('Assets.send.payDetailBtnOK')}</Text>
                                                </TouchableOpacity>
                                                :
                                                <TouchableOpacity style={{
                                                    width: "96%",
                                                    height: 40,
                                                    justifyContent: 'center',
                                                    backgroundColor: '#C6C7CB',
                                                    alignItems: 'center',
                                                    borderColor: '#C6C7CB',
                                                    borderWidth: 1,
                                                    borderRadius: 10
                                                }} onPress={sendRedEnvelope}>
                                                    <Text style={{
                                                        // marginTop: 160,
                                                        fontSize: 20,
                                                        textAlign: 'center',
                                                        color: 'white'
                                                    }}>{locale._('Assets.send.payDetailBtnOK')}</Text>
                                                </TouchableOpacity>
                                        }
                                    </View>
                                </View>
                            </View>
                        </View>
                        :null
                }
            </ImageBackground>
        </View>
    );
}
export  default RedEnvelope;
